package com.example.qu_tao.View;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.qu_tao.R;
import com.example.qu_tao.adapter.GoodsPhotoAdapter;
import com.example.qu_tao.entity.Photo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class fahuopinActivity extends AppCompatActivity implements View.OnClickListener, GoodsPhotoAdapter.OnPhotoListener {

    private RecyclerView rvGoodsPhoto;
    private ImageView back;
    private GoodsPhotoAdapter adapter;
    private List<Photo> photoList = new ArrayList<>();
    private EditText etGoodsName, etGoodsPrice, etGoodsFreight, etGoodsAddress, etGoodsStock, etGoodsMessage;
    private Button btnSend;
    private ActivityResultLauncher<Intent> mActivityResultLauncher;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fahuopin);

        // 初始化 RecyclerView
        rvGoodsPhoto = findViewById(R.id.rv_goods_photo);
        back = findViewById(R.id.back);
        etGoodsName = findViewById(R.id.et_goods_name);
        etGoodsPrice = findViewById(R.id.huopinjiage);
        etGoodsFreight = findViewById(R.id.huopinyunfei);
        etGoodsAddress = findViewById(R.id.fahuodizhi);
        etGoodsStock = findViewById(R.id.huopinkucun);
        etGoodsMessage = findViewById(R.id.et_goods_message);
        btnSend = findViewById(R.id.goods_send);

        photoList.add(new Photo());
        adapter = new GoodsPhotoAdapter(photoList);
        adapter.setPhotoListener(this);

        rvGoodsPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        back.setOnClickListener(this);
        btnSend.setOnClickListener(this);
        rvGoodsPhoto.setAdapter(adapter);

        onActivityResult();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.goods_send) {
            saveGoodsToDatabase();
        }
    }

    @Override
    public void onAdd() {
        // 启动图库选择图片
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        mActivityResultLauncher.launch(intent);
    }

    @Override
    public void onDelete(int position) {

    }


    private void onActivityResult() {
        mActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        int resultCode = result.getResultCode();
                        if (resultCode == RESULT_OK) {
                            Intent data = result.getData();
                            Uri selectedImageUri = data.getData();
                            try {
                                // 使用图片URI进行处理，例如加载到ImageView中
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                                Photo photo = new Photo();
                                photo.setBitmap(bitmap);
                                // 压缩图片尺寸
                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                Bitmap resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 0.5), (int) (bitmap.getHeight() * 0.5), true);
                                resized.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                photo.setData(outputStream.toByteArray());
                                adapter.addPhoto(photo);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void saveGoodsToDatabase() {
        String goodsName = etGoodsName.getText().toString();
        String goodsPriceStr = etGoodsPrice.getText().toString();
        String goodsFreightStr = etGoodsFreight.getText().toString();
        String goodsAddress = etGoodsAddress.getText().toString();
        String goodsStockStr = etGoodsStock.getText().toString();
        String goodsMessage = etGoodsMessage.getText().toString();

        if (goodsName.isEmpty() || goodsPriceStr.isEmpty() || goodsFreightStr.isEmpty() ||
                goodsAddress.isEmpty() || goodsStockStr.isEmpty()) {
            Toast.makeText(this, "请填写所有必填项", Toast.LENGTH_SHORT).show();
            return;
        }

        double goodsPrice = Double.parseDouble(goodsPriceStr);
        double goodsFreight = Double.parseDouble(goodsFreightStr);
        int goodsStock = Integer.parseInt(goodsStockStr);

        ContentValues goodsValues = new ContentValues();
        goodsValues.put("goods_name", goodsName);
        goodsValues.put("goods_price", goodsPrice);
        goodsValues.put("goods_freight", goodsFreight);
        goodsValues.put("goods_address", goodsAddress);
        goodsValues.put("goods_unit", "斤");
        goodsValues.put("goods_number", goodsStock);
        goodsValues.put("goods_content", goodsMessage);

        Uri goodsUri = Uri.parse("content://com.example.qu_tao.provider/goods");
        Uri insertedGoodsUri = getContentResolver().insert(goodsUri, goodsValues);

        if (insertedGoodsUri != null) {
            long goodsId = ContentUris.parseId(insertedGoodsUri);

            for (Photo photo : photoList) {
                if (photo.getData() != null) {
                    try {
                        ContentValues photoValues = new ContentValues();
                        photoValues.put("goods_img_id", goodsId);
                        photoValues.put("image", photo.getData());

                        Uri photoUri = Uri.parse("content://com.example.qu_tao.provider/photo");
                        getContentResolver().insert(photoUri, photoValues);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            Toast.makeText(this, "货品发布成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "货品发布失败", Toast.LENGTH_SHORT).show();
        }
    }
}